﻿using System.Collections.Generic;

namespace OmniKits.Extensions
{
    using NullGuard;

    public static class DictionaryExtensions
    {
        /// <summary>
        /// Try to retrieve value associated with the specified key, won't change the reference parameter if failed.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="key">The key of the value to try to retrieve.</param>
        /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; leave the current value alone if failed. This parameter have to be initialized before passed.</param>
        /// <returns>true if successful found the value with the specified key, false if failed.</returns>
        /// <exception cref="System.ArgumentNullException">key is null.</exception>
        public static bool TryGetValue<K, V>(this IDictionary<K, V> source, K key, [AllowNull]ref V value)
        {
            V tmp;

            // succeed
            if (source.TryGetValue(key, out tmp))
            {
                value = tmp;
                return true;
            }

            // or not
            return false;
        }
    }
}
